package com.snk.kof.common.thread;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author keshan
 * @date 2022-01-02 下午4:16
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadManager {

    private static final ThreadFactory THREAD_FACTORY = ThreadFactoryBuilder.create()
            .setDaemon(Boolean.FALSE)
            .setPriority(1)
            .setNamePrefix("kof-thread-manager")
            .setUncaughtExceptionHandler((t, e) -> log.error("[ThreadManager#uncaughtExceptionHandler] threadId={}, exception={}", t.getId(), e.getMessage()))
            .build();

    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            2 * Runtime.getRuntime().availableProcessors(),
            1L,
            TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(1000),
            THREAD_FACTORY,
            (r, executor) -> {
                executor.getQueue().offer(r);
                log.error("[ThreadManager#rejectedExecutionHandler] runnableInfo={}, executorInfo={}", r.toString(), executor.toString());
            }
    );

    public static ThreadPoolExecutor getThreadPool() {
        return THREAD_POOL_EXECUTOR;
    }

}
